using System;
using System.Configuration;
using System.IO;

namespace Sustainalytics.FTPReport.BusinessLogic.Logging
{
    public abstract class SimpleLoggingNameStrategy
    {
        public interface IHaveFileName
        {
            string Name(string fileName);
        }

        public abstract class HaveFileName
        {
            protected readonly string LogFolder;

            protected HaveFileName()
            {
                //TODO: pass folder path from ctor
                string resultFolder = ConfigurationManager.AppSettings["uploadFolder"];
                LogFolder = Path.Combine(resultFolder, "_log");

                CreateLogFolder();
            }

            protected int GetNumberOfFiles()
            {
                DirectoryInfo dir = new DirectoryInfo(LogFolder);
                return dir.GetFiles().Length;
            }

            protected bool CheckFileExists(string fileName)
            {
                return File.Exists(Path.Combine(LogFolder, fileName));
            }

            protected bool FolderExists(string folderName)
            {
                return Directory.Exists(LogFolder);
            }
            private void CreateLogFolder()
            {
                if (!FolderExists(LogFolder))
                    Directory.CreateDirectory(LogFolder);
            }
        }

        public class TimeStampName : HaveFileName, IHaveFileName
        {
            public string Name(string fileName)
            {
                if (CheckFileExists(fileName))
                    fileName = fileName.Replace(".txt", "") + "(" + GetNumberOfFiles() + ").txt";

                return Path.Combine(LogFolder, GetTimestamp() + fileName);
            }

            public string GetTimestamp()
            {
                return DateTime.Now.ToString("HHmmss");
            }
        }

        public class IncrementalName : HaveFileName, IHaveFileName
        {
            public string Name(string fileName)
            {
                if (CheckFileExists(fileName))
                    fileName = fileName.Replace(".txt", "") + "(" + GetNumberOfFiles() + ").txt";

                return Path.Combine(LogFolder, fileName);
            }
        }

        public class FileName : IHaveFileName
        {
            private readonly IHaveFileName _iHaveFileName;

            public FileName(IHaveFileName ihaveFileName)
            {
                _iHaveFileName = ihaveFileName;
            }
            public string Name(string filename)
            {
                return _iHaveFileName.Name(filename);
            }
        }
    }
}
